package org.zjx.app.action.route;

import org.zjx.analysis.analyze.game.GameAnalysis;
import org.zjx.app.action.window.ClickSceneAction;
import org.zjx.app.action.window.TabAction;
import org.zjx.command.entity.screen.Address;
import org.zjx.command.entity.screen.Room;
import org.zjx.command.entity.screen.Scene;
import org.zjx.command.entity.screen.TabMap;
import org.zjx.command.state.GameState;
import org.zjx.data.GameSystem;
import org.zjx.window.action.Action;
import org.zjx.window.window.IWindow;

import java.awt.*;

public class RunningAction extends Action {
    private final Address targetAddress;

    public RunningAction(IWindow targetWindow, Address targetAddress) {
        super(targetWindow, false);
        this.targetAddress = new Address(targetAddress.getCity(),targetAddress.getX() + 2,targetAddress.getY());
    }

    @Override
    protected void doExecute() throws Exception {
                Address nowAddress = getAddressNow();
        if (nowAddress.near(targetAddress, 5)) return;
        GameState gameState = targetWindow.getState().getGameState();

        if (gameState.getAddress() == null || timeOutAndNotMove(gameState, nowAddress)){
            TabMap tabMap = getTabMap(nowAddress);
            if (tabMap == null) {
                targetWindow.submitAction(new ClickSceneAction(targetWindow, targetAddress, ClickSceneAction.ClickType.SCENE));
            } else {
                targetWindow.submitAction(new TabAction(targetWindow, targetAddress));
            }
        }

        if (!nowAddress.equals(gameState.getAddress())) {
            gameState.setAddress(nowAddress);
            gameState.setRecordAddressTime(System.currentTimeMillis());
        }
    }

    private boolean timeOutAndNotMove(GameState gameState, Address nowAddress) {
        long before = stateManager.getGameState().getRecordAddressTime();
        return System.currentTimeMillis() - before > 3000 && nowAddress.equals(gameState.getAddress());
    }

    public Address getAddressNow() {
        GameAnalysis gameAnalysis = new GameAnalysis(targetWindow);
        return gameAnalysis.getAddress();
    }

    private TabMap getTabMap(Address address) {
        Scene scene = GameSystem.getInstance().getWorldManager().getScene(address.getCity());
        Room roon = GameSystem.getInstance().getWorldManager().getGlobalRoomCache().get(address.getCity());
        if (scene != null) return scene.tabMap;
        else return roon.tabMap;
    }

}